package com.pj.wisdomlogistics.ui.activity;
import android.content.ComponentName;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.blog.www.guideview.Guide;
import com.blog.www.guideview.GuideBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.HomePageInfo;
import com.pj.wisdomlogistics.mvp.contract.WisdomLogisticsContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.WisdomLogisticsPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.adapter.HomePageAdapter;
import com.pj.wisdomlogistics.ui.fragment.ApplyAccountFragment;
import com.pj.wisdomlogistics.ui.fragment.ServiceAccountFragment;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.MutiComponent;
import com.pj.wisdomlogistics.utils.SPUtils;
import com.pj.wisdomlogistics.utils.ToSign;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import butterknife.BindView;
import butterknife.OnClick;


public class MainActivity extends MvpActivity<WisdomLogisticsPresenter> implements
        WisdomLogisticsContract.View, HomePageAdapter.onItemClick, NavigationView.OnNavigationItemSelectedListener {
    @BindView(R.id.rv_main)
    RecyclerView mRvMain;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.nav_view)
    NavigationView navigationView;
    @BindView(R.id.rl_myTopBar)
    RelativeLayout mRlTopbar;
    @BindView(R.id.iv_sign)
    ImageView mIvSign;
    @BindView(R.id.iv_drawer)
    ImageView mIvDrawer;
    @BindView(R.id.iv_noData)
    ImageView mIvNoData;


    private HomePageAdapter mAdapter;

    private View headerView;
    private ImageView mIvAvatar;
    private TextView mTvUsername;
    private TextView mTvDept;
    private TextView mTvpost;
    private TextView mTvPremission;
    private long mExitTime = 0;

    private boolean isApplyView = false;


    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        ultimateBar.setColorBar(ContextCompat.getColor(this, R.color.text_blue));

        if(MyApplication.isJc){
            mIvDrawer.setVisibility(View.GONE);
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        }

        switch (MyApplication.userType) {
//            case Cons.UserType.NORMAL_ACCOUNT:
//                getSupportFragmentManager().beginTransaction().add(R.id.layout_header_view, new NormalAccountFragment()).commit();
//                break;
            case Cons.UserType.MANAGE_ACCOUNT_1:
                getSupportFragmentManager().beginTransaction().add(R.id.layout_header_view, new ServiceAccountFragment()).commit();
                break;
            case Cons.UserType.MANAGE_ACCOUNT_2:
                getSupportFragmentManager().beginTransaction().add(R.id.layout_header_view, new ServiceAccountFragment()).commit();
                break;
            case Cons.UserType.APPLY_ACCOUNT:
                getSupportFragmentManager().beginTransaction().add(R.id.layout_header_view, new ApplyAccountFragment()).commit();
                isApplyView = true;
                break;
//            case Cons.UserType.CHECK_ACCOUNT:
//                getSupportFragmentManager().beginTransaction().add(R.id.layout_header_view, new CheckAccountFragment()).commit();
//                break;
        }

        mRvMain.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mAdapter = new HomePageAdapter(this, this);
        mRvMain.setAdapter(mAdapter);
        mAdapter.setListener(this);
        mRvMain.setFocusable(false);

        //设定NavigationView菜单的选择事件
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setItemIconTintList(null);
        headerView = navigationView.getHeaderView(0);
        mIvAvatar = (ImageView) headerView.findViewById(R.id.iv_avatar);
        mTvUsername = (TextView) headerView.findViewById(R.id.tv_username);
        mTvDept = (TextView) headerView.findViewById(R.id.tv_department);
        mTvpost = (TextView) headerView.findViewById(R.id.tv_post);
        mTvPremission = (TextView) headerView.findViewById(R.id.tv_permission);


        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.default_avatar)
                .error(R.drawable.default_avatar)
                .priority(Priority.HIGH);
        Glide.with(this).load(MyApplication.user.getHeadThumb()).apply(options).into(mIvAvatar);
        mTvUsername.setText(MyApplication.user.getName());
        mTvDept.setText("");
        mTvpost.setText("");
        mTvPremission.setText("");


        if (MyApplication.user.getIsSign() == 1) {
            mIvSign.setVisibility(View.VISIBLE);
            mIvSign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToSign.sign(MainActivity.this);
                }
            });
        }

        for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
            if(TextUtils.equals(MyApplication.user.getRoleId().get(i) , Cons.RoleId.PORITION_CAR)){
                mIvSign.setVisibility(View.VISIBLE);
                mIvSign.setImageResource(R.drawable.resume);
                mIvSign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(FreeCarActivity.class);
                    }
                });
                return;
            }
        }

    }

    @Override
    public void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.home(MyApplication.userID);
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_wisdom_logistics;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }

    @OnClick({R.id.iv_drawer , R.id.iv_font})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.iv_drawer:
                if (drawer.isDrawerOpen(Gravity.LEFT)) {
                    drawer.closeDrawer(Gravity.LEFT);
                } else {
                    drawer.openDrawer(Gravity.LEFT);
                }
                break;
            case R.id.iv_font:
                int theme = 0;
                switch (SPUtils.getInt(Cons.SPCons.THEME)) {
                    case R.style.Theme_normal:
                        theme = R.style.Theme_Medium;
                        break;
                    case R.style.Theme_Medium:
                        theme = R.style.Theme_Large;
                        break;
                    case R.style.Theme_Large:
                        theme = R.style.Theme_normal;
                        break;
                }
                SPUtils.putInt(Cons.SPCons.THEME , theme);
                ActivityManagerUtil.create().finishAllActivity();
                startActivity(this.getClass());
                break;
        }
    }

    @Override
    public void editClick() {
        mAdapter.mPopWindow.dismiss();
    }

    @Override
    public void itemClick(int id , int tag) {
        Intent mIntent = null;
        switch (tag){
            case 1:
                mIntent = new Intent(this, TakeoutDetailActivity.class);
                mIntent.putExtra(Cons.TakeoutMeal.TAKEOUT_ID, id);
                break;
            case 2:
                mIntent = new Intent(this, CarDetailActivity.class);
                mIntent.putExtra(Cons.CarInfo.CAR_ID , id);
                break;
            case 3:
                mIntent = new Intent(this, ApplyDetailActivity.class);
                mIntent.putExtra(Cons.ApplyDetail.MEETING_ID, id);
                break;
            case 4:
                mIntent = new Intent(this , RepairDetailActivity.class);
                mIntent.putExtra(Cons.RepairInfo.REPAIR_ID , id);
                break;
            case 5:
                mIntent = new Intent(this , MealDetialActivity.class);
                mIntent.putExtra(Cons.MealInfo.MEAL_ID , id);
                break;
        }
        startActivity(mIntent);
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (MyApplication.isJc) {
                Intent intent = new Intent();
                ComponentName comp = new ComponentName("com.richmobi.emp", "com.cattsoft.zcpt.ui.MainActivity");
                intent.setComponent(comp);
                startActivity(intent);
                finish();
            }else{
                if (System.currentTimeMillis() - mExitTime > 2000) {
                    CustomToast.showToast(this ,"再按一次退出程序" , 1000);
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_password_manager:
                startActivity(RetPwdActivity.class);
                break;
            case R.id.nav_about_me:
                startActivity(AboutMeActivity.class);
                break;
            case R.id.nav_feedback:
                break;
            case R.id.nav_exit:
                MyApplication.logout();
                startActivity(LoginActivity.class);
                ActivityManagerUtil.create().finishActivity();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public void onSuccess(String signPath) {
        Log.e("Tag", signPath);
        dismissProgressDialog();
        MyApplication.user.setSignPath(signPath);
        CustomToast.showToast(this ,"上传签字成功" , 1000);
    }

    @Override
    public void onError(String errorMsg) {
        CustomToast.showToast(this ,errorMsg , 1000);
    }



    @Override
    public void onHomeSuccess(HomePageInfo mInfo) {
        EventBus.getDefault().post(new EventCenter<>(
                isApplyView ? Cons.Badger.BADGER_APPLY : Cons.Badger.BADGER_SERVICE , mInfo.getCount()
        ));

        if(mInfo == null || mInfo.getList().size() == 0){
            mIvNoData.setVisibility(View.VISIBLE);
            mRvMain.setVisibility(View.GONE);
        }else{
            mAdapter.setList(mInfo.getList());
        }
    }


    public void showGuideView() {
        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(mIvSign)
                .setAlpha(150)
                .setHighTargetCorner(20)
                .setOverlayTarget(false)
                .setOutsideTouchable(false);
        builder.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override public void onShown() {
            }

            @Override public void onDismiss() {
            }
        });

        builder.addComponent(new MutiComponent());
        Guide guide = builder.createGuide();
        guide.setShouldCheckLocInWindow(true);
        guide.show(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1){
            String path = data.getStringExtra("path");
            if(TextUtils.isEmpty(path)) return;
            //上传签名
            mPresenter.saveSignPath(
                    MyApplication.userID ,
                    new File(path)
            );

            showProgressDialog();
        }
    }
}
